#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import web
import json
import urllib2

from users import *
from weibo import *
import config

container = {}

def generate_error(message):
	u = 'https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&scope=%s&stage=weibo&forelogin=true&display=mobile' % \
		(config.client_id, config.redirect_uri, config.scope)
	return json.dumps({'error': message, 'auth_url': u}, sort_keys=False)

def build_callback_page(message):
	page = '<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>weibo_callback</title></head><body><script type="text/javascript">window.parent.postMessage(JSON.stringify(%s), "*");</script></body></html>' % (json.dumps(message))
	return page
	
class initialize:
	def GET(self):
		query = web.input()

		try:
			uid = int(query.uid)
			user = container['users'].get(uid)
			weibos = container['weibo'].load(uid);
			web.header('Content-Type', 'application/json,charset=utf-8')
			return json.dumps({'user': {'uid': user['uid'], 'name': user['name'], 'icon': user['icon']},
							   'weibos': weibos})
		except Exception as e:
			return generate_error('no valid user token')

class refresh:
	def GET(self):
		query = web.input()
		uid = int(query.uid)
		min_weibo_id = int(query.min_weibo_id)

		weibos = []
		try:
			weibos = container['weibo'].refresh(uid, min_weibo_id)
		except e:
			pass
		web.header('Content-Type', 'application/json,charset=utf-8')
		return json.dumps({'weibos': weibos})

class loadmore:
	def GET(self):
		query = web.input()
		uid = int(query.uid)
		max_weibo_id = int(query.max_weibo_id)

		weibos = []
		try:
			weibos = container['weibo'].loadmore(uid, max_weibo_id)
		except:
			pass
		web.header('Content-Type', 'application/json,charset=utf-8')
		return json.dumps({'weibos': weibos})

# 处理OAuth2认证OK
# 回调参数
# code   string 	用于调用access_token，接口获取授权后的access token
# state  string 	如果传递参数，会回传该参数。 
#
class oauth2_callback:
	def GET(self):
		query = web.input()
		data = 'client_id=%d&client_secret=%s&grant_type=authorization_code&code=%s&redirect_uri=%s' % \
			(config.client_id, config.client_secret, query['code'], config.redirect_uri)
		print 'oauth2_callback, data:', data
		request = urllib2.urlopen('https://api.weibo.com/oauth2/access_token', data)
		result = json.JSONDecoder().decode(request.read())
		
		message = {}
		if result.access_token:
			container['users'].save({'uid': result.uid, 'token': result.access_token, 'expire': (int(time.time()) + expires_in)})
			message['uid'] = result.uid;
		else:
			message['error'] = result.error
		
		web.header('Content-Type', 'text/html;charset=utf-8')
		return build_callback_page(message)

class oauth2_cancel:
	def GET(self):
		return 'weibo_cancel'

routes = (
	'/api/weibo/initialize', 'initialize',
	'/api/weibo/refresh', 'refresh',
	'/api/weibo/loadmore', 'loadmore',
	'/api/weibo/oauth2_callback', 'oauth2_callback',
	'/api/weibo/oauth2_cancel', 'oauth2_cancel'
)

if "__main__" == __name__:
	container['db'] = web.database(dbn='sqlite', db=config.db)
	container['users'] = users(container['db'])
	container['weibo'] = weibo(container['db'], container['users'])

	app = web.application(routes, globals(), False)
	app.run()
